import 'dart:math';

import 'package:flame/components.dart';
import 'package:flame/particles.dart';
import 'package:flutter/material.dart';

mixin Particleable {
  final Random _random = Random();

  Vector2 randomVector() {
    Vector2 base = Vector2.random(_random); //  (0, 0) ~ (1, 1)
    Vector2 fix = Vector2(-0.5, -0.5);
    base = base + fix; //  (-0.5, -0.5) ~ (0.5, 0.5)
    return base;
  }

  Color generateRandomColor() {
    //FFECB3
    final r = _random.nextInt(105) + 150; // 0-255 之间的随机整数
    final g = _random.nextInt(105) + 150;
    final b = _random.nextInt(105) + 5;
    return Color.fromRGBO(r, g, b, 0.8);
  }

  ParticleSystemComponent createParticle(Vector2 position) {
    Vector2 temp = position.clone();
    Particle particle = Particle.generate(
        count: 16,
        applyLifespanToChildren: false,
        lifespan: 1,
        generator: (i) {
          return AcceleratedParticle(
            child: CircleParticle(
              radius: 1,
              paint: Paint()..color = generateRandomColor(),
            ),
            acceleration: randomVector() * 50,
            speed: randomVector() * 50,
            position: temp + randomVector(),
            lifespan: _random.nextDouble() + 0.5,
          );
        });

    final ParticleSystemComponent psc =
        ParticleSystemComponent(particle: particle);
    return psc;
  }
}
